#include "canthread.h"
#include <QDebug>
#include <QList>

VCI_BOARD_INFO vbi;
canThread::canThread(QObject *parent)
    : QObject{parent}
{
    stopped = false;
    deviceType = 4;
    debicIndex = 0;
    baundRate = 250;
    debicCom = 0;
}

bool canThread::openCan()
{
    int nDeviceType = deviceType; /* USBCAN-2A或USBCAN-2C或CANalyst-II */
    int nDeviceInd = debicIndex; /* 第1个设备 */
    int nCANInd = debicCom; /* 第1个通道 */
    int nplnfo = plnfo;
    DWORD dwRel;
    //dwRel = VCI_UsbDeviceReset(nDeviceType, nDeviceInd,0);/*CAN复位操作*/
    dwRel = VCI_OpenDevice(nDeviceType, nDeviceInd, nCANInd);/*启动CAN*/
    dwRel = VCI_ResetCAN(nDeviceType, nDeviceInd, nCANInd);
    dwRel = VCI_ResetCAN(nDeviceType, nDeviceInd, nCANInd+1);
    if(dwRel != 1)
    {
        emit SIGcanopefai();
        return false;
    }
    else
        qDebug()<<"open success";
        emit SIGcansuc();

    dwRel = VCI_ClearBuffer(nDeviceType, nDeviceInd, nCANInd);
    dwRel = VCI_ClearBuffer(nDeviceType, nDeviceInd, nCANInd+1);
    VCI_INIT_CONFIG vic;
    vic.AccCode=0x80000008;
//    vic.AccCode=0x00000003;
    vic.AccMask=0xFFFFFFFF;
    vic.Filter=1;
    vic.Mode=0;
    switch (baundRate) {
    case 10:
        vic.Timing0=0x31;
        vic.Timing1=0x1c;
        break;
    case 20:
        vic.Timing0=0x18;
        vic.Timing1=0x1c;
        break;
    case 40:
        vic.Timing0=0x87;
        vic.Timing1=0xff;
        break;
    case 50:
        vic.Timing0=0x09;
        vic.Timing1=0x1c;
        break;
    case 80:
        vic.Timing0=0x83;
        vic.Timing1=0xff;
        break;
    case 100:
        vic.Timing0=0x04;
        vic.Timing1=0x1c;
        break;
    case 125:
        vic.Timing0=0x03;
        vic.Timing1=0x1c;
        break;
    case 200:
        vic.Timing0=0x81;
        vic.Timing1=0xfa;
        break;
    case 250:
        vic.Timing0=0x01;
        vic.Timing1=0x1c;
        break;
    case 400:
        vic.Timing0=0x80;
        vic.Timing1=0xfa;
        break;
    case 500:
        vic.Timing0=0x00;
        vic.Timing1=0x1c;
        break;
    case 666:
        vic.Timing0=0x80;
        vic.Timing1=0xb6;
        break;
    case 800:
        vic.Timing0=0x00;
        vic.Timing1=0x16;
        break;
    case 1000:
        vic.Timing0=0x00;
        vic.Timing1=0x14;
        break;
    case 33:
        vic.Timing0=0x09;
        vic.Timing1=0x6f;
        break;
    case 66:
        vic.Timing0=0x04;
        vic.Timing1=0x6f;
        break;
    case 83:
        vic.Timing0=0x03;
        vic.Timing1=0x6f;
        break;
    default:
        break;
    }
    dwRel = VCI_InitCAN(nDeviceType, nDeviceInd, nCANInd, &vic);
    dwRel = VCI_InitCAN(nDeviceType, nDeviceInd, nCANInd+1, &vic);
    if(dwRel !=1)
    {
        qDebug()<<"init fail";
        return false;
    }
    else
        qDebug()<<"init success";
        emit SIGCanOpen();

    dwRel = VCI_ReadBoardInfo(nDeviceType, nDeviceInd, &vbi);
    if(dwRel != 1)
    {
        return false;
    }
    else
    {
    }

    if(VCI_StartCAN(nDeviceType, nDeviceInd, nCANInd) !=1)
    {
        return false;
    }
    else
        qDebug()<<"start"<<nCANInd<<"success:";

    int comid = nCANInd+1;
    if(VCI_StartCAN(nDeviceType, nDeviceInd, comid) !=1)
    {
        return false;
    }
    else
        qDebug()<<"start"<<comid<<"success:";
    stCan();
    return true;

}

void canThread::sleep(unsigned int msec)
{
    QTime dieTime = QTime::currentTime().addMSecs(msec);
    while( QTime::currentTime() < dieTime )
        QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
}

void canThread::stopCan()
{
    stopped = true;
    closeCan();
    //emit SIGcansuc();
    emit SIGCanClose();
}

void canThread::closeCan()
{
    VCI_CloseDevice(deviceType, debicIndex);
    qDebug()<<"closed CAN";
    emit SIGcanclosuc();
}

void canThread::sendData(int ID, std::vector<int> vec)
{
    DWORD dwRel;
    VCI_CAN_OBJ vco[48];
    vco[0].ID = ID;
    vco[0].RemoteFlag = 0;
    vco[0].ExternFlag = 1;
    vco[0].DataLen = 8;
    for(int j = 0;j<8;j++)
    vco[0].Data[j] = vec[j];
    dwRel = VCI_Transmit(deviceType, debicIndex, debicCom, vco,1);

    QDateTime dateTime= QDateTime::currentDateTime();
    QString time = dateTime.toString("yyyy-MM-dd hh:mm:ss.zzz");
    QString xVal =QString("%1").arg(ID, 4, 16, QLatin1Char('0')).toUpper();
    QString data;
    int a;
    for(int i=0;i<8;i++)
    {
        a=vec[i];
        data = data.append(QString("%1").arg(a, 2, 16, QLatin1Char('0')));
    }
    QByteArray data1 = data.toLatin1();
    emit SIGtomain(time+"__"+xVal+"__"+data);
    emit SIGtosqlstosendat(xVal,data1);
    qDebug()<<data;
}

void canThread::stCan()
{
    while(!stopped)
    {
        DWORD dwRel;
        VCI_CAN_OBJ vco[2500];
        dwRel = VCI_Receive(4, 0, 0, vco,500,0);
        if(dwRel > 0)
        {
            dataProcess(vco,dwRel);
            emit SIGtosqlstorecdat(vco,dwRel);
            if(mingling2 == true)
            {
                emit SIGtoSS(vco,dwRel);
            }
        }
        else if(dwRel == -1)
        {
            qDebug()<<"设备不存在或USB掉线";
        }
        sleep(60);
    }
    stopped = false;
}

void canThread::stCan1()
{
    while(!stopped)
    {
        DWORD dwRel;
        VCI_CAN_OBJ vco[2500];
        dwRel = VCI_Receive(4, 0, 1, vco,500,0);
        //dwRel = VCI_Receive(4, 0, 1, vco,500,0);
        if(dwRel > 0)
        {
            dataProcess(vco,dwRel);
            emit SIGtosqlstorecdat(vco,dwRel);
            if(mingling2 == true)
            {
                emit SIGtoSS(vco,dwRel);
            }
        }
        else if(dwRel == -1)
        {
            qDebug()<<"设备不存在或USB掉线";
        }
        sleep(60);
    }
    stopped = false;
}

void canThread::dataProcess(VCI_CAN_OBJ *vci, DWORD dwRel)
{
    QString xVal;
    QDateTime dateTime= QDateTime::currentDateTime();
    QString time = dateTime.toString("yyyy/MM/dd-hh:mm:ss.zzz ");
    unsigned int i;
    int a;
    QString data2;
    for(i = 0;i<dwRel;i++)
    {
        int id = vci[i].ID;
        xVal = QString("%1").arg(id, 8, 16, QLatin1Char('0')).toUpper();
        data2 = 0;
        for(int j = 0;j<8;j++)
        {
           a = vci[i].Data[j];
           data2 = data2.append(QString("%1").arg(a, 2, 16, QLatin1Char('0')));
        }
        if(xVal == "11F10001")
        {
            emit Recdata1_1(data2);
            DCDC1_1 = data2;
        }
        if(xVal == "11F20001")
        {
            emit Recdata1_2(data2);
            DCDC1_2 = data2;
        }        
        QString DCDCAll = DCDC1_1+DCDC1_2;
        emit TCPSendCANData(DCDCAll);
        emit SIGCanRec();
        //qDebug()<<data2;
    }
}

void canThread::timerEvent(QTimerEvent *e)
{
//    if(CANConnect == false)
//    {
//        openCan();
//        CANConnect = true;
//    }
}

//void canThread::stoSenData(QString data)
//{
//    QList<QString> m_ListAllSrt;
//    m_ListAllSrt.clear();
//    m_ListAllSrt = {data};
//    for(int i = 0; i < m_ListAllSrt.size(); i++)
//    {
//        for(int j = i + 1; i < m_ListAllSrt.size(); i++)
//        {
//            if(m_ListAllSrt.at(i) == m_ListAllSrt.at(j))
//            {
//                m_ListAllSrt.removeAt(j);
////                m_ListAllSrt.append("1");
//                j--;

//            }
//        }
//    }

//    QString filename;
//    QDateTime timefile = QDateTime::currentDateTime();//获取系统现在的时间
//    QString datefile = timefile.toString("yyyy.MM.dd");//设置显示的格式
//    filename += datefile;
//    filename += ".txt";
//    QFile file("D:/SendData/QTCellTestFile/LocalFiles/CanRecvData/"+filename);
//    if(!file.open(QIODevice::WriteOnly | QIODevice::Text |QIODevice::Append))
//    {
//        qDebug()<<file.errorString();
//        return;
//    }
//    //写入文件
//    QString hh = "\n";
//    QString t1 =data+"   "+hh;
//    file.write(t1.toUtf8());
//    //关闭文件
//    file.flush();
//    file.close();
//}
